package edu.sdjzu.exam.config;

import cn.dev33.satoken.stp.StpInterface;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SaTokenStpInterface implements StpInterface {

    private final JdbcTemplate jdbcTemplate;

    public SaTokenStpInterface(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Long userId = Long.parseLong(loginId.toString());
        String sql = "SELECT p.permission_name FROM Permissions p " +
                "JOIN Role_Permissions rp ON p.permission_id = rp.permission_id " +
                "JOIN User_Roles ur ON rp.role_id = ur.role_id " +
                "WHERE ur.user_id = ?";
        return jdbcTemplate.query(sql, new Object[]{userId}, (rs, rowNum) -> rs.getString("permission_name"));
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Long userId = Long.parseLong(loginId.toString());
        String sql = "SELECT r.role_name FROM Roles r " +
                "JOIN User_Roles ur ON r.role_id = ur.role_id " +
                "WHERE ur.user_id = ?";
        return jdbcTemplate.query(sql, new Object[]{userId}, (rs, rowNum) -> rs.getString("role_name"));
    }
}
